import axios from 'axios'
// import { getToken } from '@/utils/local.js'
import { removeToken } from '@/utils/local.js'
import store from '@/store/index.js'
import router from '@/router/index.js'
import { Message } from 'element-ui'
const request = axios.create({
  baseURL: process.env.VUE_APP_URL,
  withCredentials: true
})
// 添加拦截器
// 添加请求拦截器
request.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    // 添加token请求
    config.headers.token = `${store.state.user.token}`
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  function (response) {
    if (response.data.code === 200) {
      return response
    } else if (response.data.code === 206) {
      Message.error('登录失效，请重新登录')
      removeToken('token')
      router.push('/login?redirect=' + window.location.href.split('#')[1])
      return Promise.reject(response.data.message)
    } else {
      Message.error(response.data.message)
    }
    return Promise.reject(response.data.message)
  },
  function (error) {
    // 对响应错误做点什么

    return Promise.reject(error)
  }
)

export default request
